import sys, re
from qt import *
sys.path.append("commands")

title = "TextPlay 0.1"

def toHtml(qstr):
    return qstr.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\n", "<br>")

class CommandLineEdit(QLineEdit):
    def __init__(self, *args):
        apply(QLineEdit.__init__, (self,) + args)
        self.index = -1
        self.entered = []
        self.connect(self, SIGNAL("textChanged(const QString &)"), self._commandTextChanged)
        self.connect(self, SIGNAL("returnPressed()"), self._commandEntered)
    def _commandEntered(self):
        self.entered.insert(0, self.text())
        self.index = -1
    def _commandTextChanged(self, s):
        if self.isModified():
            self.index = -1
    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Up and self.index < len(self.entered)-1:
            if self.index == -1:
                self.oldText = self.text()
                self.oldCursorPosition = self.cursorPosition()
            self.index += 1
            self.setText(self.entered[self.index])
        elif e.key() == Qt.Key_Down and self.index >= 0:
            self.index -= 1
            if self.index > -1:
                self.setText(self.entered[self.index])
            else:
                self.setText(self.oldText)
                self.setCursorPosition(self.oldCursorPosition)
        QLineEdit.keyPressEvent(self, e)
            

class TextPlayWindow(QMainWindow):
    def __init__(self, *args):
        apply(QMainWindow.__init__, (self,) + args)
        self.resize(500, 500)
        self.setCaption(title)
        self.innerWidget = QWidget(self)
        self.setCentralWidget(self.innerWidget)
        self.vlayout = QVBoxLayout(self.innerWidget)
        
        self.log = QTextEdit(self.innerWidget)
        self.log.setFocusPolicy(QWidget.TabFocus)
        self.log.setReadOnly(True)
        self.log.append("<p><h1>" + title + "</h1></p>")
        self.vlayout.addWidget(self.log)
        
        self.innerWidget2 = QWidget(self.innerWidget)
        self.hlayout = QHBoxLayout(self.innerWidget2)
        self.hlayout.setMargin(0);
        self.command = CommandLineEdit(self.innerWidget2)
        self.command.setFocus()
        self.connect(self.command, SIGNAL("returnPressed()"), self._commandEntered)
        self.hlayout.addWidget(QLabel("> ", self.innerWidget2))
        self.hlayout.addWidget(self.command)
        self.vlayout.addWidget(self.innerWidget2)
        
        if len(sys.argv) > 1:
            game = sys.argv[1]
        else:
            game, ok = QInputDialog.getText("TextPlay", "Enter game name:")
            if not ok:
                self.close()
                return
        
        self.game = __import__(str(game))
        self.append("<p><large>" + str(toHtml(self.game.processor.init())) + "</large></p>")
        self.statusWidgets = []
        for a in xrange(0, len(self.game.processor.statusEntries)):
            self.statusWidgets.append(QLabel(self.statusBar()))
            self.statusWidgets[a].setMargin(2)
            self.statusWidgets[a].setText(self.game.processor.statusEntries[a])
            self.statusBar().addWidget(self.statusWidgets[a], 1)
    
    def append(self, text):
        self.log.append(text)
        QTimer.singleShot(0, self._scrollToBottom) 
    
    def _scrollToBottom(self):
        self.log.verticalScrollBar().setValue(self.log.verticalScrollBar().maxValue())
    
    def _commandEntered(self):
        text = self.command.text()
        self.command.clear()
        if text == "exit" or text == "quit":
            qApp.quit()
        else:
            ret = toHtml(QString(self.game.processor.process(str(text))))
            if ret:
                self.append("<p><u>" + str(text) + "</u><br><large>" + str(ret) + "</large></p>")
            self.statusBar()
            for a in xrange(0, len(self.game.processor.statusEntries)):
                self.statusWidgets[a].setText(self.game.processor.statusEntries[a])

def main(args):
    app=QApplication(args)
    win=TextPlayWindow()
    win.show()
    app.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()"))
    app.exec_loop()

if __name__=="__main__":
    main(sys.argv)

